<template>
  <div>
    <rj-table
      class="project-list"
      :columns="columns"
      :data-source="tableData"
      :loading="loading"
      :rowKey="(row) => row.buildingId"
      :pagination="pagination"
      @change="handleTableChange"
      :scroll="{ x: true }"
      @changeSelectColums="changeSelectColums"
    >
      <!-- 项目名称 -->
      <div slot="projectName" slot-scope="text, record">
        <div v-if="record.simulationNetwork" class="experience-flag">
          {{ $t('groupOperate.getT') }}
        </div>
        <div class="row-name">
          <div style="position: relative">
            <a
              @click="() => projectInfo(record)"
              :class="[
                'row-project',
                record.simulationNetwork ? 'simulation' : '',
              ]"
              :title="text"
              >{{ text }}</a
            >
            <icon-font
              v-if="record.enetConflictState == 'CONFLICT'"
              class="fonfict-icon"
              type="ic-tree-device"
            ></icon-font>
          </div>

          <div>
            <icon-font
              type="ic-prof-map"
              class="row-icon"
              @click="() => toMap(record)"
            ></icon-font>
            <icon-font
              type="ic-edit"
              class="row-icon"
              :title="$t('groupOperate.eidtproject')"
              @click="() => editProjectBase(record)"
            ></icon-font>
          </div>
        </div>
      </div>
      <!-- 告警 -->
      <div slot="warn" slot-scope="text, record">
        <span @click="() => warnView(record)" class="row-hover">
          {{ text }}
        </span>
        <VirtualAlarm
          :groupId="record.buildingId"
          v-if="record.simulationNetwork"
        ></VirtualAlarm>
      </div>
      <!-- 在线用户 -->
      <div slot="sta" slot-scope="text, record">
        <div @click="() => clientView(record)" class="row-hover">
          {{ text }}
        </div>
      </div>
      <!-- AP -->
      <div slot="ap" slot-scope="text, record">
        <div
          @click="() => deviceList(record, 'AP')"
          class="row-hover"
          v-html="getDevice(record, 'AP')"
        >
          <!-- <span class="online">{{ getDevice(record,) }}</span
                >/{{ text }} -->
        </div>
      </div>
      <!-- AC -->
      <div slot="ac" slot-scope="text, record">
        <div
          @click="() => deviceList(record, 'AC')"
          class="row-hover"
          v-html="getDevice(record, 'AC')"
        ></div>
      </div>

      <!-- 网关 -->
      <div slot="gateway" slot-scope="text, record">
        <div
          @click="() => deviceList(record, 'GATEWAY')"
          class="row-hover"
          v-html="getDevice(record, 'GATEWAY')"
        ></div>
      </div>
      <!-- 交换机 -->
      <div slot="switch" slot-scope="text, record">
        <div
          @click="() => deviceList(record, 'SWITCH')"
          class="row-hover"
          v-html="getDevice(record, 'SWITCH')"
        ></div>
      </div>
      <!-- 无线路由 -->
      <div slot="wr" slot-scope="text, record">
        <div
          @click="() => deviceList(record, 'WR')"
          class="row-hover"
          v-html="getDevice(record, 'WR')"
        ></div>
      </div>
      <!-- 无线路由 -->
      <div slot="bridge" slot-scope="text, record">
        <div
          @click="() => deviceList(record, 'BRIDGE')"
          class="row-hover"
          v-html="getDevice(record, 'BRIDGE')"
        ></div>
      </div>
      <!-- 防火墙 -->
      <div slot="firewall" slot-scope="text, record">
        <div
          @click="() => deviceList(record, 'FIREWALL')"
          class="row-hover"
          v-html="getDevice(record, 'FIREWALL')"
        ></div>
      </div>
      <!-- 未知设备 -->
      <div slot="unknown" slot-scope="text, record">
        <div
          @click="() => unknownDevice(record)"
          class="row-hover"
          v-html="getDevice(record, 'UNKNOWN')"
        ></div>
      </div>

      <!-- 操作 -->
      <div slot="action" slot-scope="text, record">
        <a-space>
          <a style="margin-right: 10px" @click="() => wirelessConfig(record)">{{
            $t('common.monitorBmWireless')
          }}</a>
          <a @click="() => projectInfo(record)">{{ $t('common.topo') }}</a>
          <a v-if="userType == 'SHARE'" @click="() => unShare(record)">{{
            $t('groupOperate.notmannger')
          }}</a>
          <a
            v-else
            :title="$t('groupOperate.shareProject')"
            @click="() => share(record)"
            >{{ $t('common.share') }}</a
          >
          <a
            :title="$t('groupOperate.deleteProject')"
            v-if="userType != 'SHARE'"
            @click="() => deletProject(record)"
            >{{ $t('common.delete') }}</a
          >
        </a-space>
      </div>
    </rj-table>
    <!-- 分享网络弹窗 -->
    <ShareGroup
      v-if="showShareGroup"
      :groupInfo="clickRecord"
      @closeCallback="closeShareGCallBack"
    />
  </div>
</template>
<script>
import { requestHttp, maccApi } from '@utils/index';
import { RjTable } from '@components';
import { mapState } from 'vuex';
import { colums, localKey } from './columns';
// import { i18nRender } from '@/locales';
import ShareGroup from '@views/common/groupManage/shareGroup/index.vue';

//混入 进行  常量的 转换
import i18nMixin from '@mixin/i18n-mixin';

import VirtualAlarm from '../virtualAlarm/virtualAlarm.vue';
import _ from 'lodash';
import { i18nRender } from '@/locales';

export default {
  name: 'GlobalNetwork',
  mixins: [i18nMixin],
  props: {
    searchKey: String,
  },
  data() {
    return {
      tableData: [],

      pagination: {
        total: 0,
        showSizeChanger: false,
        showQuickJumper: false,
      },
      loading: false,
      showShareGroup: false,
      clickRecord: null,
    };
  },

  components: {
    'rj-table': RjTable,
    VirtualAlarm,
    ShareGroup,
  },
  computed: {
    ...mapState('User', ['userType']),
    ...mapState('Theme', ['theme']),
    ...mapState('Account', ['scene']),
    ...mapState('Layout', ['newVueFrame']),

    // groupName() {
    //   return this.searchKey;
    // },
    columns() {
      colums.forEach((item) => {
        item.title = this.$t(`tableHeader.${item.dataIndex}`);
      });
      return colums;
    },
  },
  activated() {
    console.log('==================userType', this.userType);
    this.intColumnsShow();
    this.fetch();
  },
  watch: {
    searchKey: {
      handler() {
        this.keySearchProject();
      },
      //immediate: true,
    },
    '$store.state.Group.groupTree': {
      handler() {
        this.fetch();
      },
      immediate: true,
    },
    '$store.state.devices.deviceTotal': {
      handler() {
        this.fetch();
      },
      immediate: true,
    },
  },
  methods: {
    keySearchProject: _.debounce(function () {
      this.fetch();
    }, 200),
    /**
     * @description:表格操作函数
     * @param {*} pagination 分页对象
     * @param {*} filters 过滤对象
     * @param {*} sorter 排序对象
     * @return {*}
     */
    handleTableChange(pagination, filters, sorter) {
      console.log(pagination);
      const pager = { ...this.pagination };
      pager.current = pagination.current;
      this.pagination = pager;
      console.log('==============', sorter, filters);
      this.fetch({
        results: pagination.pageSize,
        page: pagination.current,
        sortField: sorter.field,
        sortOrder: sorter.order,
        ...filters,
      });
    },
    /**
     * @description: 查询网络列表
     * @param {*} params
     * @return {*}
     */
    async fetch(params) {
      const defaultparams = { results: 10, page: 1 };
      params = { ...defaultparams, ...params };

      this.loading = true;
      const fetchParams = {
        ignoreLogbiz: true,
        enet: true,
        includeFitap: true,
      };

      let api = `${maccApi.PROJECT_LIST_GET_API.replace(
        '{page}',
        params.page
      ).replace('{per_page}', params.results)}`;

      if (this.searchKey) {
        //fetchParams.groupName = this.searchKey;
        api += '&keyword=' + encodeURI(this.searchKey);
      }
      if (params.sortField && params.sortOrder) {
        // fetchParams.sortField = params.sortField;
        // fetchParams.sortType = params.sortOrder == 'ascend' ? 'asc' : 'desc';
        api += '&sort_field=' + params.sortField + 'All';
        api += '&sort_type=' + (params.sortOrder == 'ascend' ? 'asc' : 'desc');
      }

      const res = await requestHttp({
        api: api,
        method: 'GET',
      });
      this.loading = false;
      this.tableData = res.dataList || [];
      this.pagination.total = res.totalCount || 0;
      console.log('------ds-ad-as-d-asd-', this.tableData);

      let dataobj = res.dataList;
      console.log('dataobj', dataobj);

      if (this.searchKey == '') {
        this.$store.dispatch('User/setProject', this.pagination.total);
      }
      const groupList = this.getBuildList();
      this.getSta(groupList);
    },
    getBuildList() {
      const groupList = [];
      for (let i = 0; i < this.tableData.length; i++) {
        groupList.push(this.tableData[i].buildingId);
      }

      return groupList;
    },
    async getSta(groupList) {
      if (groupList.length == 0) {
        return;
      }
      const res = await requestHttp({
        api: `${maccApi.NETWORK_STA_GET_API.replace(
          '{group_list}',
          groupList.join()
        )}`,
        method: 'GET',
        module: 'logbiz',
      });

      if (res && res.code == 0) {
        const staMap = this.getStaMap(res.list || []);
        this.updataStaData(staMap);
      }
    },
    getStaMap(list) {
      let map = {};
      for (let i = 0; i < list.length; i++) {
        map[list[i].buildingId] = list[i].totalUserCount;
      }
      return map;
    },
    updataStaData(staMap) {
      for (let i = 0; i < this.tableData.length; i++) {
        const item = this.tableData[i];
        const buildingId = item.buildingId;
        this.tableData[i].staCount = staMap[buildingId] || 0;
      }
      this.tableData = [...this.tableData];
    },
    /**
     * @description: 分享项目
     * @param {*} record
     * @return {*}
     */
    share(record) {
      if (this.newVueFrame || window.top?.base?.mpm === 'intl_public') {
        this.clickRecord = { ...record, groupId: record.buildingId };
        this.showShareGroup = true;
      } else {
        this.$iframeMsg('SHARE_NETWORK', {
          groupId: record.buildingId,
          groupName: record.name,
        });
      }
    },
    /**
     * @description: 取消项目分享
     * @param {*} record
     * @return {*}
     */
    unShare(record) {
      this.$iframeMsg('UNSHARE_NETWORK', {
        groupId: record.buildingId,
        totalNum: this.pagination.total,
      });
    },
    /**
     * @description: 无线配置
     * @param {*} record
     * @return {*}
     */
    wirelessConfig(record) {
      console.log('无线配置', record);
      if (
        this.theme == 'RUIYI_V2' ||
        window === window.top ||
        window.top?.base?.mpm === 'intl_public'
      ) {
        this.$store.commit('Group/SET_GROUPID', record.buildingId);
        this.$router.replace({
          path: '/monitor_config_device_wireless_ssid_menu',
        });
      } else {
        this.$iframeMsg('GOTO_HASH', {
          hash: 'config_group_groupconfig_menu',
          groupId: record.buildingId,
          param: {},
        });
      }
    },
    /**
     * @description: 跳转项目详情
     * @param {*} record
     * @return {*}
     */
    projectInfo(record) {
      console.log('跳转项目详情', record);
      if (window === window.top) {
        this.$store.commit('Group/SET_GROUPID', record.buildingId);
        if (
          this.$store.state.Theme.theme === 'RUIYI_V2' ||
          process.env.VUE_APP_MACC_ENV == 'INTL'
        ) {
          //睿易2.0主题跳转到工作台
          this.$router.replace({
            path: '/monitor_project_workbarn_menu',
          });
        } else {
          this.$router.replace({
            path: '/monitor_overview_networkdetails_menu',
          });
        }
      } else {
        this.$iframeMsg('GOTO_HASH', {
          hash: 'monitor_overview_networkdetails_menu',
          groupId: record.buildingId,
          param: {},
        });
      }
    },
    /**
     * @description: 跳转设备列表
     * @param {*} record
     * @param {*} commonType
     * @return {*}
     */
    deviceList(record, commonType) {
      if (window === window.top) {
        this.toVueDevicesIfarme(record, commonType);
      } else {
        this.toOldDevicesIfarme(record, commonType);
      }
    },
    toVueDevicesIfarme(record, commonType) {
      this.$store.commit('Group/SET_GROUPID', record.buildingId);
      if (this.scene == 'MACC5') {
        this.$router.replace({
          path: '/monitor_devices_device_menu',
          query: { commontype: commonType },
        });
      } else {
        switch (commonType) {
          case 'AP':
            this.$router.replace({
              path: '/monitor_devices_accesspoint_menu',
            });
            break;
          case 'SWITCH':
            this.$router.replace({
              path: '/monitor_devices_switch_menu',
            });
            break;
          case 'GATEWAY':
            this.$router.replace({
              path: '/monitor_devices_gateway_menu',
            });
            break;
          case 'AC':
            this.$router.replace({
              path: '/monitor_devices_ac_menu',
            });
            break;
          case 'WR':
            this.$router.replace({
              path: '/monitor_devices_wr_menu',
            });
            break;
          case 'BRIDGE':
            this.$router.replace({
              path: '/monitor_devices_bridge_menu',
            });
            break;
          case 'FIREWALL':
            this.$router.replace({
              path: '/monitor_devices_firewall_menu',
            });
            break;
        }
      }
    },
    toOldDevicesIfarme(record, commonType) {
      if (this.theme == 'RUIYI' && top.window.menuscene === 'MACC5') {
        this.$iframeMsg('GOTO_HASH', {
          hash: 'monitor_devices_device_menu',
          groupId: record.buildingId,
          param: { commontype: commonType },
        });
      } else {
        switch (commonType) {
          case 'AP':
            this.$iframeMsg('GOTO_HASH', {
              hash: 'monitor_devices_accesspoint_menu',
              groupId: record.buildingId,
              param: {},
            });
            break;
          case 'SWITCH':
            this.$iframeMsg('GOTO_HASH', {
              hash: 'monitor_devices_switch_menu',
              groupId: record.buildingId,
              param: {},
            });
            break;
          case 'GATEWAY':
            this.$iframeMsg('GOTO_HASH', {
              hash: 'monitor_devices_gateway_menu',
              groupId: record.buildingId,
              param: {},
            });
            break;
          case 'AC':
            this.$iframeMsg('GOTO_HASH', {
              hash: 'monitor_devices_ac_menu',
              groupId: record.buildingId,
              param: {},
            });
            break;
          case 'WR':
            this.$iframeMsg('GOTO_HASH', {
              hash: 'monitor_devices_wr_menu',
              groupId: record.buildingId,
              param: {},
            });
            break;
          case 'BRIDGE':
            this.$iframeMsg('GOTO_HASH', {
              hash: 'monitor_devices_bridge_menu',
              groupId: record.buildingId,
              param: {},
            });
            break;
          case 'FIREWALL':
            this.$iframeMsg('GOTO_HASH', {
              hash: 'monitor_devices_firewall_menu',
              groupId: record.buildingId,
              param: {},
            });
            break;
        }
      }
    },
    /**
     * @description: 未知设备
     * @param {*} record
     * @return {*}
     */
    unknownDevice(record) {
      this.$iframeMsg('UNKNOW_DEVICE', {
        groupId: record.buildingId,
      });
    },
    /**
     * @description: 在线用户信息
     * @param {*} record
     * @return {*}
     */
    clientView(record) {
      if (window === window.top || window.top?.base?.mpm === 'intl_public') {
        this.$store.commit('Group/SET_GROUPID', record.buildingId);
        if (this.theme != 'NOC') {
          this.$router.replace({
            path: '/monitor_clients_clients_menu',
          });
        } else {
          this.$router.replace({
            path: '/monitor_clients_clientlist_menu',
          });
        }
      } else {
        if (this.theme == 'RUIYI') {
          this.$iframeMsg('GOTO_HASH', {
            hash: 'monitor_clients_clients_menu',
            groupId: record.buildingId,
            param: {},
          });
        } else {
          this.$iframeMsg('GOTO_HASH', {
            hash: 'monitor_clients_clientlist_menu',
            groupId: record.buildingId,
            param: {},
          });
        }
      }
    },
    /**
     * @description:告警界面
     * @param {*} record
     * @return {*}
     */
    warnView(record) {
      if (window === window.top || window.top?.base?.mpm === 'intl_public') {
        this.$store.commit('Group/SET_GROUPID', record.buildingId);
        this.$router.replace({
          path: '/monitor_overview_alarm_menu',
          query: { level: 'warn_level' },
        });
      } else {
        this.$iframeMsg('GOTO_HASH', {
          hash: 'monitor_overview_alarm_menu',
          groupId: record.buildingId,
          param: { level: 'warn_level' },
        });
      }
    },
    /**
     * @description: 编辑项目基础信息
     * @param {*} record
     * @return {*}
     */
    editProjectBase(record) {
      const params = { groupId: record.buildingId, ...record };
      console.log('params', params);
      if (window === window.top || window.top?.base?.mpm === 'intl_public') {
        const groupEdit = {
          groupId: params.groupId,
          name: params.name,
          businessType: params.businessType,
          timezone: params.timezone,
        };
        console.log('groupEdit', groupEdit);
        this.$EventBus.$emit('Add_NETWORK', {
          groupEdit: groupEdit,
        });
      } else {
        this.$iframeMsg('PROJECT_EDIT', {
          params: params,
        });
      }
    },
    toMap(record) {
      this.$emit('mapAction', record.buildingId);
    },
    /**
     * @description: 删除项目
     * @param {*} record
     * @return {*}
     */
    deletProject(record) {
      const self = this;
      console.log('record', record);
      let confirmContent = '';
      if (record.totalCount > 0) {
        confirmContent = this.$t('groupOperate.deletdevices');
      }
      this.$confirm({
        title: i18nRender('system.delete'),
        content: `${confirmContent}${this.$t('groupOperate.sure')}"${
          record.name
        }"${this.$t('groupOperate.sure')}？`,
        okText: i18nRender('deviceDetail.comfirmOk'),
        okType: 'danger',
        cancelText: i18nRender('system.cancle'),
        async onOk() {
          const results = await requestHttp({
            api: `${maccApi.PROJECT_DEL_API.replace(
              '{groupId}',
              record.buildingId
            )}`,
            method: 'DELETE',
          });
          if (results && results.code == 0) {
            self.$message.success(i18nRender('groupOperate.deleteSuc'));
            self.$store.dispatch('Group/updataGroupTree');
            const projectTotal = self.$store.state.User.project;
            self.$store.dispatch('User/setProject', projectTotal - 1);
            self.$store.dispatch('User/getWarnCount');
            self.$store.dispatch('devices/getDeviceTotal', {
              include_fitap: true,
            });
            self.pagination.current = 1;
            self.fetch();
          } else {
            self.$message.error(results.msg);
          }
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    },
    //列表显示列配置
    changeSelectColums(colums) {
      console.log('表头变更==========', colums);
      const userId = this.$store.state.User.userInfo.accountId;
      colums = colums || [];
      const cols = [];
      for (let i = 0; i < colums.length; i++) {
        cols.push(colums[i].key);
      }
      const globalNetworkSet = window.localStorage.getItem(localKey);
      if (globalNetworkSet) {
        let setting = JSON.parse(globalNetworkSet);
        setting[userId] = cols;
        window.localStorage.setItem(localKey, JSON.stringify(setting));
      } else {
        let setting = {};
        setting[userId] = cols;
        window.localStorage.setItem(localKey, JSON.stringify(setting));
      }
    },
    //初始化显示列表
    intColumnsShow() {
      const columnsSet = window.localStorage.getItem(localKey);
      const userId = this.$store.state.User.userInfo.accountId;
      if (
        columnsSet &&
        JSON.parse(columnsSet) &&
        JSON.parse(columnsSet)[userId]
      ) {
        const showColumns = JSON.parse(columnsSet)[userId] || [];
        this.columns.forEach((item) => {
          item.showColums = showColumns.indexOf(item.key) > -1;
        });
        this.columns = [...this.columns];
      }
      console.log('初始化显示列表', columnsSet);
    },
    getDevice(record, commonType) {
      let fitApOnCount = 0,
        fitApTotalCount = 0;
      if (commonType == 'AP') {
        fitApOnCount = record.fitApOnCount || 0;
        fitApTotalCount = record.fitApTotalCount || 0;
      }

      if (record.commonTypeList) {
        const commonTypeList = record.commonTypeList;
        const currentDeviceType = commonTypeList.find((item) => {
          return item.commonType == commonType;
        });

        if (currentDeviceType) {
          if (commonType == 'AP') {
            return `<span class="online">${
              currentDeviceType.onCount + fitApOnCount
            }</span
          >/${currentDeviceType.totalCount + fitApTotalCount}`;
          } else {
            return `<span class="online">${currentDeviceType.onCount}</span
          >/${currentDeviceType.totalCount}`;
          }
        } else {
          if (commonType == 'AP') {
            return `<span class="online">${fitApOnCount}</span
          >/${fitApTotalCount}`;
          } else {
            return '-';
          }
        }
      } else {
        if (commonType == 'AP') {
          return `<span class="online">${fitApOnCount}</span
          >/${fitApTotalCount}`;
        } else {
          return '-';
        }
      }
    },
    //关闭分享网络弹窗
    closeShareGCallBack() {
      this.showShareGroup = false;
    },
  },
};
</script>
<style lang="less">
.project-list {
  .ant-table-row-cell-break-word {
    overflow: hidden;
    position: relative;
  }
  .ant-table-thead > tr > th,
  .ant-table-tbody > tr > td {
    padding: 10px 5px;
  }
}
</style>
<style lang="less" scoped>
.experience-flag {
  position: absolute;
  background-color: @onlineColor;
  color: #fff;
  transform: rotate(316deg) scale(0.8);
  border-radius: 2px;
  padding: 0 20px;
  font-size: 12px;
  height: 25px;
  line-height: 25px;
  top: -2px;
  left: -23px;
}
.row-name {
  display: flex;
  justify-content: space-between;

  .row-project {
    overflow: hidden;
    max-width: 100%;
    text-overflow: ellipsis;
    //white-space: nowrap;
    display: inline-block;
    text-align: left;
    //max-height: 50px;
    &.simulation {
      margin-left: 15px;
    }
  }
  .fonfict-icon {
    position: absolute;
    right: -8px;
    top: -15px;
    color: @colorRed;
  }
  .row-icon {
    margin-right: 5px;
    color: #959595;
    &:hover {
      cursor: pointer;
    }
  }
}

.row-hover {
  cursor: pointer;
  &:hover {
    text-decoration: underline;
  }
  /deep/ .online {
    color: @onlineColor;
  }
}
/deep/ .ant-space {
  display: inline-flex;
  width: 213px;
}

/deep/ .ant-space-align-center {
  align-items: center;
  justify-content: center;
}
</style>
